package com.lang8.util.mail;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lang8.util.web.WebHolder;
import com.lang8.util.web.WrapperResponse;

public class MailUtil {
	private static final String testContent = "<div style=\"color:red;\">Email Test</div>";
	private String mailer = "sendhtml";
	private String mailhost = "smtp.163.com";
	private String from = "\"Zhang, Norris\" <arkwright@163.com>";
	private String to = "arkwright@sina.com";
	private String subject = "email subject";
	private String templatePage = "/emailtemplate/activateemail.jsp";
	public MailUtil(){
	}
	public void send(){
		try {
			Properties props = new Properties();
			if (mailhost != null) {
				props.put("mail.smtp.host", mailhost);
			}
			props.setProperty("mail.transport.protocol", "smtp");
			props.setProperty("mail.smtp.auth", "true");
			Session session = Session.getInstance(props, new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					PasswordAuthentication auth = new PasswordAuthentication("arkwright", "271118");
					return auth;
				}
			});
			
			Message msg = new MimeMessage(session);
			if (from != null)
				msg.setFrom(new InternetAddress(from));
			else
				msg.setFrom();
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(to, false));
			msg.setSubject(subject);
			String content = getContent();
			msg.setDataHandler(new DataHandler(new ByteArrayDataSource(content, "text/html")));
			msg.setHeader("X-Mailer", mailer);
			msg.setSentDate(new Date());
			
			Transport.send(msg);
			System.out.println("successful");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private String getContent() throws Exception {
		HttpServletResponse response = WebHolder.responsetTL.get();
		HttpServletRequest request = WebHolder.requestTL.get();
		if (response == null || request == null) {
			return testContent;
		}
		WrapperResponse wrapperResponse = new WrapperResponse(response);
		request.getRequestDispatcher(templatePage).include(request, wrapperResponse);
		return wrapperResponse.getContent();
	}
	public static void main(String[] args) {
		MailUtil mailUtil = new MailUtil();
		mailUtil.send();
	}
}
